import {Component, OnInit} from '@angular/core';
import 'rxjs/add/operator/switchMap';
import {ProjectStep} from "../entity/ProjectStep";
import {FileUploader} from "ng2-file-upload";
import {ProjectAddService} from "../service/project.add.service";
import {Params, Router} from "@angular/router";
import {ActivatedRoute} from "@angular/router";
import {ProjectFindService} from "../service/project.find.service";
import {Project} from "../entity/Project";
import {CommonMsg} from "../../shared/entity/CommonMsg";
import {CommonIp} from "../../user/entity/Ip";

declare var $: any;
@Component({
  selector:'project-step',
  templateUrl:'./project-step.html',

})
export  class ProjectStepComponent extends CommonIp
implements OnInit
{
  public  uploadFiles = [];
  public projectStep:ProjectStep = new ProjectStep();
  public  uploader:FileUploader;
  private project:Project;
  constructor(private projectAddService: ProjectAddService, private activatedRouter: ActivatedRoute,private router: Router,
              private projectService:ProjectFindService){
    super();
    //noinspection TypeScriptUnresolvedFunction
    this.uploader = new FileUploader({
      url: this.userIp+"/fileUpload",
      method: "POST",
      itemAlias: "uploadedfile",
      removeAfterUpload:true
    });
  }
  selectedFileOnChanged() {
    // 这里是文件选择完成后的操作处理
    this.uploader.queue[0].upload(); // 开始上传
    this.uploader.queue[0].onSuccess = (response, status, headers) => {
      // 上传文件成功
      if (status == 200) {
        // 上传文件后获取服务器返回的数据
        let tempRes = JSON.parse(response);
        // this.uploadFiles.push(this.userimgIp+tempRes.fileUrl);
        var imglistnew=$("#myeditor img");//获取ID为div里面的所有img
        for(var i=0;i<imglistnew.length;i++){ //循环为每个img设置
          var url =  imglistnew[i].getAttribute("src");
          if(url.indexOf("data:")!=-1){
            imglistnew[i].setAttribute("src",this.userimgIp+tempRes.fileUrl);
          }
        }
        // this.uploadFiles = [];
        var imglistnew=$("#myeditor img");//获取ID为div里面的所有img
        for(var i=0;i<imglistnew.length;i++){ //循环为每个img设置
          var url =  imglistnew[i].getAttribute("src");
          this.uploadFiles.push(url);
        }

      }else {
        // 上传文件后获取服务器返回的数据错误
      }
    };


  }



  ngOnInit(): void {

    this.activatedRouter.params
    // (+) converts string 'id' to a number
      .switchMap((params: Params) =>this.initParam(params["id"])).subscribe();


    $("#myeditor").wysiwyg();
  }

  private initParam(param: any):Promise<string> {
    this.uploadFiles = [];
    if(sessionStorage.getItem("Isupdate")=="true") {
      this.projectStep = sessionStorage.getItem("projectStep") == null ? this.projectStep : JSON.parse(sessionStorage.getItem("projectStep"));
      $("#myeditor").html(this.projectStep.content);
      var imglist=$("#myeditor img");//获取ID为div里面的所有img

      for(var i=0;i<imglist.length;i++){ //循环为每个img设置
        var url =  imglist[i].getAttribute("src");
        this.uploadFiles.push(url);
      }
      this.projectStep.project = new Project();
    }
    this.projectStep.project.id=param;
    return param;
  }

  onSubmit (){
    var content = document.getElementById("myeditor").innerHTML;

    // var imglist=$("#myeditor img");//获取ID为div里面的所有img
    // for(var i=0;i<imglist.length;i++){ //循环为每个img设置
    //   imglist[i].setAttribute("src",this.uploadFiles[i]);
    // }
    this.projectStep.content = document.getElementById("myeditor").innerHTML;

    if(sessionStorage.getItem("Isupdate")=="true"){
      this.projectAddService.updateProgectStep(this.projectStep).then(commonMsg=>
      {
        this.router.navigate(['/project/index/',this.projectStep.project.id]);
      });
      sessionStorage.removeItem("Isupdate");

    }else {
      this.projectStep.id = "";
      this.projectAddService.saveProjectStep(this.projectStep).then(commonMsg=>
        {
          this.handleResult(commonMsg);
        }
      );
    }

  }

  public handleResult(commonMsg:CommonMsg<any>){
    if(commonMsg!=null&&commonMsg.code==200){
      $.jBox.tip("步骤添加成功!");
      this.project = commonMsg.entity;
      this.router.navigate(['/project/index/',this.projectStep.project.id]);
    }else{
      $.jBox.tip("步骤添加失败!");
    }
  }

}
